﻿using B.S.BasicData.Infrastructure;
using B.S.BasicData.Infrastructure.Implement;
using B.S.BasicData.Infrastructure.Interfance;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Reflection;
using System.Text;

namespace B.S.BasicData.Read.Extensions
{
    public static class ServicesCollectionExtensions
    {
        public static IServiceCollection AddServices(this IServiceCollection services)
        {
            services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "B.S.BasicData.Read.xml", true));
            services.AddScoped<SCDbContext>();
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));
            services.AddMediatR(x => x.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly()));
            //services.AddAutoMapper(typeof(Myautomapper));
            return services;
        }




        /// <summary>
        /// 字符串的连接
        /// </summary>
        /// <typeparam name="TDbContext"></typeparam>
        /// <param name="services"></param>
        /// <param name="connectionString"></param>
        /// <param name="enableSqLlog"></param>
        /// <returns></returns>
        public static IServiceCollection AddDbContextServices<SCDbContext>(this IServiceCollection services, string? connectionString, bool enableSqLlog) where SCDbContext : DbContext
        {
            return services.AddDbContext<SCDbContext>(builder =>
            {
                builder.UseSqlServer(connectionString, action =>
                {
                    action.EnableRetryOnFailure(
                            maxRetryCount: 10,
                            maxRetryDelay: TimeSpan.FromSeconds(60),
                            errorNumbersToAdd: null
                        );
                }).EnableSensitiveDataLogging();
                if (enableSqLlog)
                {
                    builder.UseLoggerFactory(LoggerFactory.Create(configure =>
                    {
                        configure
                        .AddFilter((category, level) => category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
                        .AddConsole();
                    }));
                }
            });
        }

        /// <summary>
        /// 注册JWT 
        /// </summary>
        /// <param name="collection"></param>
        /// <param name="builder"></param>
        public static void AddJWT(this IServiceCollection collection, WebApplicationBuilder builder)
        {
            builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["JwtSettings:SecretKey"]);
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        //验证发布者
                        ValidateIssuer = true,
                        ValidIssuer = builder.Configuration["JwtSettings:Issuer"],

                        //验证接收者
                        ValidateAudience = true,
                        ValidAudience = builder.Configuration["JwtSettings:Audience"],

                        //验证是否过期
                        ValidateLifetime = true,

                        //验证私钥
                        IssuerSigningKey = new SymmetricSecurityKey(secretByte)
                    };
                });
        }





    }

}
